package com.smrtcold.dev.task;

import com.alibaba.fastjson.JSONObject;
import com.smrtcold.dev.dto.dev.base.Point;
import com.smrtcold.dev.dto.dev.task.CondenserGroup;
import com.smrtcold.dev.dto.dev.task.DevTask;
import lombok.extern.log4j.Log4j2;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;


/**
 * 冷凝器--水泵--调整
 */
@Log4j2
@Service
public class CondenserJob extends BaseJob implements Job {


    //纪念堂缓存没有全局，避免数据交叉
    private static HashMap<String, LocalDateTime> localDateTimeHashMap = new HashMap<>();//上次控制时间--每个任务可能不一样

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        DevTask task = (DevTask) context.getJobDetail().getJobDataMap().get("TASK");
        super.mainRun(task);
    }


    /**
     * 执行任务
     *
     * @param
     * @param
     * @throws Exception
     */
    public boolean run(DevTask task) throws Exception {
        String parameters = task.getParameters();
        List<CondenserGroup> pointGroups = JSONObject.parseArray(parameters, CondenserGroup.class);
        int successCount = 0, i = 1;
        for (CondenserGroup pointGroup : pointGroups) {
            logContert.append(String.format("第%s组：%s\n", i, pointGroup.getName()));
            if (this.ctlic(pointGroup)) {
                successCount++;
            }
            logContert.append("\n");
            i++;
        }
        return successCount == pointGroups.size();

    }

    /**
     * 执行控制逻辑
     *
     * @param pointGroup
     * @throws Exception
     */
    public boolean ctlic(CondenserGroup pointGroup) throws Exception {
        //1.获取默认参数配置
        //初始化配置参数
        HashMap<String, Object> taskParams = this.initParams(pointGroup.getExtParams());
        boolean isok = false;
        int model = (Integer) taskParams.get("计算模型");
        switch (model) {
            case 0:
                //变频版本-压缩机运行，控制风机依次启停 ---水泵启动
                isok = this.mode0(pointGroup, taskParams);
                break;
            case 1:
                break;
            default:

                break;
        }
        return isok;
    }

    public boolean mode0(CondenserGroup pointGroup, HashMap<String, Object> taskParams) throws Exception {
        //2.获取压机运行状态
        HashMap<String, Object> dataCache = new HashMap<>();

        long compRunCount = this.getRunCount(pointGroup.getComp(), dataCache);
        //3.获取冷凝器--风机运行情况
        long fanRunCount = this.getRunCount(pointGroup.getFanStatus(), dataCache);
        //水泵运行数量
        long bengRunCount = this.getRunCount(pointGroup.getBengStatus(), dataCache);
        // 获取上下限压力
        //  float max = this.getFloat(taskParams, "目标压力上限"), min = this.getFloat(taskParams, "目标压力下限");
        //获取实际压力，冷凝器温度
        float sjpressure = this.getFloat(taskParams, "实际压力"), condTemp = this.getFloat(taskParams, "冷凝器温度");
        taskParams.put("compRunCount", compRunCount);
        taskParams.put("fanRunCount", fanRunCount);
        taskParams.put("bengRunCount", bengRunCount);
        if (0 == compRunCount && 0 == fanRunCount && 0 == bengRunCount) {
            return true;
        }

        boolean isCompul = 1 == this.getInt(taskParams, "强制跟随机组");
        this.log("压机运行：%s，泵运行：%s，冷凝风扇运行：%s，冷凝器-排气压力：%s，冷凝器温度：%s, 强制跟随机组：%s \r\n", compRunCount, bengRunCount, fanRunCount, sjpressure, condTemp, isCompul);
        // 执行强启强停逻辑----未考虑断线后操作---
        if (isCompul) {
            //
            if (compRunCount == 0) {
                if (fanRunCount > 0) {
                    //此时需要停止冷凝分机
                    float tagevalue = getFloat(taskParams, "风机停止压力");
                    log("风机:run:%s-->0,设置压力:%s", fanRunCount, tagevalue);
                    this.setPoint(pointGroup.getSetPoint(), taskParams, tagevalue);
                }else{
                    float tagevalue = getFloat(taskParams, "风机待机压力");
                    log("风机:run:%s-->0,设置压力:%s", fanRunCount, tagevalue);
                    this.setPoint(pointGroup.getSetPoint(), taskParams, tagevalue);
                }
                if (bengRunCount > 0 && null != pointGroup.getBengset()) {
                    float tagevalue = this.getFloat(taskParams, "水泵停止压力");
                    this.setPoint(pointGroup.getBengset(), taskParams, tagevalue);
                }else{

                }
            } else {
                if (fanRunCount == 0) {
                    float tagevalue = getFloat(taskParams, "风机启动压力");
                    this.setPoint(pointGroup.getSetPoint(), taskParams, tagevalue);
                }
                if (bengRunCount == 0) {
                    float tagevalue = this.getFloat(taskParams, "水泵启动压力");
                    this.setPoint(pointGroup.getBengset(), taskParams, tagevalue);
                }
            }
        } else {

            if (taskParams.containsKey("风机设定压力")) {
                String[] setvalues = taskParams.get("风机设定压力").toString().split(",");
                float[] tagevalue = new float[setvalues.length];
                for (int j = 0; j < setvalues.length; j++) {
                    tagevalue[j] = Float.parseFloat(setvalues[j]);
                }
                this.setPoint(pointGroup.getSetPoint(), taskParams, tagevalue);
            }
            if(taskParams.containsKey("水泵设置压力")){
                String[] setvalues = taskParams.get("风机设定压力").toString().split(",");
                float[] tagevalue = new float[setvalues.length];
                for (int j = 0; j < setvalues.length; j++) {
                    tagevalue[j] = Float.parseFloat(setvalues[j]);
                }
                this.setPoint(pointGroup.getBengset(), taskParams, tagevalue);
            }

        }
        return true;
    }


    private void setPoint(Point point, HashMap<String, Object> taskParams, float... tagepressure) throws Exception {
        String devid = point.getDevid();
        boolean isMidf = point.getAddres().contains("@");
        Float max = this.getFloat(taskParams, "目标压力上限"), min = this.getFloat(taskParams, "目标压力下限");
        String[] _addres = isMidf ? point.getAddres().split("@")[0].split(",") : point.getAddres().split(",");
        String[] _names = isMidf ? point.getName().split("@")[0].split(",") : point.getName().split(",");

        List<Float> data = this.getData(devid, point.getAddres());
        StringBuffer buffer = new StringBuffer(" 旧设定参数： ");
        for (int i = 0; i < _names.length; i++) {
            buffer.append(_names[i]).append(":").append(data.get(i) + " , ");
        }
        buffer.append("\r\n");
        this.log(buffer.toString(), "");
        for (int i = 0; i < _addres.length; i++) {
            float value = tagepressure.length < i ? tagepressure[0] : tagepressure[i];
            this.write(devid, _addres[i], _names[i], value, data.get(i), max, min);
        }

    }


//    /**
//     *
//     * @param pointGroup
//     * @param status:0            需要停止，  1：需要启动  2：偏差启动
//     * @param tagepressure：需要控制的值
//     * @throws Exception
//     */
//    private void setPoint(CondenserGroup pointGroup, int status, float tagepressure, HashMap<
//            String, Object> taskParams) throws Exception {
//        //  float sjpressure = this.getFloat(taskParams, "实际压力");
//        Point point = pointGroup.getSetPoint();
//        String devid = pointGroup.getDevid();
//
//        List<Float> data = this.getData(devid, point.getAddres());
//        StringBuffer buffer = new StringBuffer(" 当前风机设定： ");
//        String[] names = point.getName().replaceAll("@", ",").split(",");
//        for (int i = 0; i < names.length; i++) {
//            buffer.append(names[i]).append(":").append(data.get(i) + " , ");
//        }
//        buffer.append("\r\n");
//        this.log(buffer.toString(), "");
//        //
//
//        boolean isCompul = 1 == this.getInt(taskParams, "强制跟随机组");
//        Float max = this.getFloat(taskParams, "目标压力上限"), min = this.getFloat(taskParams, "目标压力下限");
//
//        boolean isMidf = point.getAddres().contains("@");
//        String[] _addres = isMidf ? point.getAddres().split("@")[0].split(",") : point.getAddres().split(",");
//        String[] _names = isMidf ? point.getName().split("@")[0].split(",") : point.getName().split(",");
//
//        //  int fanRunCount = getInt(taskParams, "fanRunCount");
//        if (2 == status) {
//            //异常启动
//            String[] sets = taskParams.get("风机浮动偏差").toString().split(",");
//            for (int i = 0; i < _addres.length; i++) {
//                this.write(devid, _addres[i], _names[i], tagepressure + Float.parseFloat(sets[i]), data.get(i), max, min);
//            }
//        } else if (0 == status) {
//            //直接设置参数
//            for (int i = 0; i < _addres.length; i++) {
//                this.write(devid, _addres[i], _names[i], tagepressure, data.get(i), max, min);
//            }
//        } else {
//            //强制跟随寄宿制
//            if (isCompul) {
//                for (int i = 0; i < _addres.length; i++) {
//                    this.write(devid, _addres[i], _names[i], tagepressure, data.get(i), max, min);
//                }
//            } else {
//                String[] sets = taskParams.get("风机设定压力").toString().split(",");
//                for (int i = 0; i < _addres.length; i++) {
//                    this.write(devid, _addres[i], _names[i], Float.parseFloat(sets[i]), data.get(i), max, min);
//                }
//            }
//        }
////
////        }
//
//
//    }
//
//    private void setBen(CondenserGroup pointGroup, int status, long benstatus, float tagepressure, HashMap<
//            String, Object> taskParams, HashMap<String, Object> dataCache) throws Exception {
//        //float sjpressure = this.getFloat(taskParams, "实际压力");
//        //1.获取水泵设定参数
//        Point point = pointGroup.getBengset();
//        String devid = pointGroup.getDevid();
//        List<Float> data = this.getData(devid, point.getAddres());
//
//        boolean isMidf = point.getAddres().contains("@");
//        Float max = this.getFloat(taskParams, "目标压力上限"), min = this.getFloat(taskParams, "目标压力下限");
//        String[] _addres = isMidf ? point.getAddres().split("@")[0].split(",") : point.getAddres().split(",");
//        String[] _names = isMidf ? point.getName().split("@")[0].split(",") : point.getName().split(",");
//
//        if (2 == status) {
//            String[] sets = taskParams.get("水泵浮动偏差").toString().split(",");
//            for (int i = 0; i < _addres.length; i++) {
//                this.write(devid, _addres[i], _names[i], tagepressure + Float.parseFloat(sets[i]), data.get(i), max, min);
//            }
//        } else {
//            for (int i = 0; i < _addres.length; i++) {
//                this.write(devid, _addres[i], _names[i], tagepressure, data.get(i), max, min);
//            }
//        }
//
//
//    }


}
